package dper.study.codes.concurrent.model;

import org.apache.log4j.Logger;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created by leichen on 2017/3/21.
 */
public class ProConBufferBlockQueue implements ProConBuffer {
    Logger logger = Logger.getLogger(ProConBufferBlockQueue.class) ;

    private int bufferLen = 10 ;
    /**
     * BlockingQueue实现是线程安全的
     */
    private BlockingQueue<Integer> buffer = new ArrayBlockingQueue<Integer>(bufferLen) ;

    public void set(int i) {
        try {
            buffer.put(i) ;
            logger.info(Thread.currentThread()+"\tproducer add "+i+" in buffer\tNow size " + buffer.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public int get() throws InterruptedException {
        int head = buffer.take() ;
        logger.info(Thread.currentThread()+"\tconsumer consume "+ head+" from buffer\tNow size " + buffer.size() );
        return head;
    }
}
